package com.graduation.springbootinit.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.graduation.springbootinit.common.BaseResponse;
import com.graduation.springbootinit.common.ErrorCode;
import com.graduation.springbootinit.common.ResultUtils;
import com.graduation.springbootinit.mapper.MonthlyStoreSalesMapper;
import com.graduation.springbootinit.mapper.OrderItemMapper;
import com.graduation.springbootinit.mapper.StoreMapper;
import com.graduation.springbootinit.model.entity.ShopPart.MonthlyStoreSales;
import com.graduation.springbootinit.model.entity.ShopPart.OrderItem;
import com.graduation.springbootinit.model.entity.ShopPart.Store;
import com.graduation.springbootinit.service.MonthlyStoreSalesService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class MonthlyStoreSalesServiceImpl implements MonthlyStoreSalesService {

    @Resource
    private MonthlyStoreSalesMapper monthlyStoreSalesMapper;

    @Resource
    private OrderItemMapper orderItemMapper;

    @Resource
    private StoreMapper storeMapper;

    @Value("${shop.commission.rate}")
    private Integer commissionRate;

    @Override
    public void calculateAndUpdateMonthlySales(Integer year, Integer month) {
        // 获取所有商铺
        List<Store> stores = storeMapper.selectList(null);

        // 遍历每个商铺，计算其月度销售数据
        for (Store store : stores) {
            // 查询该商铺在指定月份的所有订单项
            List<OrderItem> orderItems = orderItemMapper.getMonthlyOrderItems(store.getId(), year, month);

            // 计算总销售额
            BigDecimal totalSales = BigDecimal.ZERO;
            for (OrderItem item : orderItems) {
                totalSales = totalSales.add(item.getTotalPrice());
            }

            // 计算平台佣金
            BigDecimal commissionAmount = totalSales.multiply(new BigDecimal(commissionRate)).divide(new BigDecimal(100));

            // 更新或创建月度销售记录
            MonthlyStoreSales monthlySales = monthlyStoreSalesMapper.getStoreMonthlySales(
                    store.getId(), year, month);

            if (monthlySales == null) {
                monthlySales = new MonthlyStoreSales();
                monthlySales.setStoreId(store.getId());
                monthlySales.setStoreName(store.getName());
                monthlySales.setYear(year);
                monthlySales.setMonth(month);
                monthlySales.setCreatedAt(LocalDateTime.now());
            }

            monthlySales.setTotalSales(totalSales);
            monthlySales.setCommissionAmount(commissionAmount);
            monthlySales.setUpdatedAt(LocalDateTime.now());

            if (monthlySales.getId() == null) {
                monthlyStoreSalesMapper.insert(monthlySales);
            } else {
                monthlyStoreSalesMapper.updateById(monthlySales);
            }
        }
    }

    @Override
    public BaseResponse<List<MonthlyStoreSales>> getMonthlyStoreSales(Integer year, Integer month) {
        if (year == null || month == null) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        List<MonthlyStoreSales> salesList = monthlyStoreSalesMapper.getMonthlyStoreSales(year, month);
        return ResultUtils.success(salesList);
    }

    @Override
    public BaseResponse<Page<MonthlyStoreSales>> getStoreSalesHistory(Long storeId, Integer pageNum, Integer pageSize) {
        if (storeId == null || pageNum == null || pageSize == null) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        Page<MonthlyStoreSales> page = new Page<>(pageNum, pageSize);
        Page<MonthlyStoreSales> salesPage = monthlyStoreSalesMapper.getStoreSalesHistory(page, storeId);
        return ResultUtils.success(salesPage);
    }

    @Override
    public BaseResponse<BigDecimal> getTotalSalesByMonth(Integer year, Integer month) {
        if (year == null || month == null) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        BigDecimal totalSales = monthlyStoreSalesMapper.getTotalSalesByMonth(year, month);
        return ResultUtils.success(totalSales != null ? totalSales : BigDecimal.ZERO);
    }

    @Override
    public BaseResponse<List<MonthlyStoreSales>> getYearlyStoreSales(Integer year) {
        if (year == null) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        List<MonthlyStoreSales> salesList = monthlyStoreSalesMapper.getYearlyStoreSales(year);
        return ResultUtils.success(salesList);
    }

    @Override
    public BaseResponse<MonthlyStoreSales> getStoreMonthlySales(Long storeId, Integer year, Integer month) {
        if (storeId == null || year == null || month == null) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        MonthlyStoreSales sales = monthlyStoreSalesMapper.getStoreMonthlySales(storeId, year, month);
        return ResultUtils.success(sales);
    }
}